import DataModel from './components/DataModel';
import ApiModel from './components/ApiModel';
import AggModel from './components/AggModel';
import { defineComponent } from 'vue';
import { MciCard, MciTabs, MciButton, MciMessage, MciDialog } from '@/components/base';
import { postDataCfgExport, postDataCfgImport } from '@/api';
import FileSaver from 'file-saver';
import { ElUpload } from 'element-plus';

export default defineComponent(() => {
  const tabs = [
    {
      label: '普通数据集',
      name: 'dataModel'
    },
    {
      label: '模型API',
      name: 'apiModel'
    },
    {
      label: '聚合数据集',
      name: 'aggModel'
    }
  ];
  const activeTab = ref('dataModel');
  const dataModelRef = ref();
  const apiModalRef = ref();
  const aggModelRef = ref();
  // 多选
  const multipleSelection = ref<any[]>([]);
  // 导出
  const loadingBtn = ref(false);
  // 导入
  const visibleImport = ref(false);
  const fileList = ref([]);
  return () => (
    <div class="w-full relative affix-container">
      <div class="sticky top-0 left-0 z-100 bg-white px-16">
        <div class="flex justify-between items-center">
          <MciTabs v-model={activeTab.value} tabs={tabs} type={'normal-theme'} />
          <div class="flex">
            <MciButton
              icon="mci-icon-add"
              type="primary"
              link={false}
              onClick={() => {
                if (activeTab.value === 'dataModel') {
                  dataModelRef.value && dataModelRef.value.handleEdit();
                } else if (activeTab.value === 'apiModel') {
                  apiModalRef.value?.handleEdit();
                } else {
                  aggModelRef.value && aggModelRef.value.handleEdit();
                }
              }}>
              新增
            </MciButton>
            {activeTab.value === 'dataModel' && (
              <>
                <MciButton
                  icon="mci-icon-upload"
                  type="info"
                  link={false}
                  loading={loadingBtn.value}
                  onClick={async () => {
                    const ids = multipleSelection.value.map((item) => item.id);
                    if (ids && ids.length) {
                      try {
                        loadingBtn.value = true;
                        const res = await postDataCfgExport(ids);
                        if (res) {
                          const blob = new Blob([JSON.stringify(res, null, 2)], { type: 'application/json' });
                          FileSaver.saveAs(blob, `数据源`);
                        }
                      } catch (error) {
                        console.log(error);
                      } finally {
                        loadingBtn.value = false;
                      }
                    }else{
                      MciMessage({
                        message: '请选择要导出的数据源',
                        type: 'info'
                      });
                    }
                  }}>
                  导出
                </MciButton>
                <MciButton
                  icon="mci-icon-download"
                  type="info"
                  link={false}
                  onClick={() => {
                    visibleImport.value = true;
                    fileList.value = [];
                  }}>
                  导入
                </MciButton>
              </>
            )}
          </div>
        </div>
      </div>
      <div style={{ width: 'calc(100% - 0px)' }}>
        <MciCard class="w-full pt-0">
          {activeTab.value === 'dataModel' && (
            <DataModel
              ref={dataModelRef}
              onSelection={(selection) => {
                // 多选数据更新
                multipleSelection.value = selection;
              }}
            />
          )}
          {activeTab.value === 'apiModel' && <ApiModel ref={apiModalRef} />}
          {activeTab.value === 'aggModel' && <AggModel ref={aggModelRef} />}
        </MciCard>
        {visibleImport.value && (
          <MciDialog
            title={'导入数据源'}
            draggable={true}
            confirmHandle={() => {
              visibleImport.value = false;
            }}
            modelValue={true}
            width={500}
            customClass="max-height-dialog">
            {{
              default() {
                return (
                  <ElUpload fileList={fileList} class="upload-demo" limit={1} accept={'.json'} drag={false} auto-upload={false}>
                    {{
                      default() {
                        return <div></div>;
                      },
                      trigger() {
                        return (
                          <>
                            <MciButton>选择数据源文件</MciButton>
                          </>
                        );
                      },
                      tip() {
                        return (
                          <>
                            <div class="el-upload__tip">限制上传1个文件，格式为 json</div>
                          </>
                        );
                      }
                    }}
                  </ElUpload>
                );
              },
              footer() {
                return (
                  <>
                    <MciButton onClick={() => (visibleImport.value = false)}>取消</MciButton>
                    <MciButton
                      type="primary"
                      onClick={() => {
                        if (fileList.value && fileList.value.length) {
                          const file = fileList.value[0]?.raw;
                          if (file) {
                            const reader = new FileReader();
                            reader.onload = async (e) => {
                              try {
                                const result = e.target?.result;
                                if (result) {
                                  const json = JSON.parse(result);
                                  if (json) {
                                    await postDataCfgImport(json);
                                    dataModelRef.value && dataModelRef.value.refreshList();
                                  }
                                  visibleImport.value = false;
                                }
                              } catch (error) {
                                console.error('error', error);
                              }
                            };
                            reader.readAsText(file);
                          }
                        }
                      }}>
                      确定
                    </MciButton>
                  </>
                );
              }
            }}
          </MciDialog>
        )}
      </div>
    </div>
  );
});
